var pattern = new RegExp(/\?DocEntry=(\S*)/g);
var idx = pattern.exec(window.location.href);

var Data02 = [], Data03 = [];

var DocEntry = $('input[data-field="ItemDocEntry"]'),
    DocStatus = $('select[data-field="ItemDocStatus"]'),
    DocDate = $('input[data-field="ItemDocDate"]'),
    Comment = $('textarea[data-field="ItemComment"]'),
    grid02 = $('#jgTable02');

$(function(){
    gridInit02();
    requestAjax(); 
    $("li[data-opt='add']").on('click', addCode);
    $("li[data-opt='back']").on('click', back);  
    $('a[opt-data="jg_upload"]').on('click', uploadSKU); 
    $("#js_submit, li[data-opt='save']").on("click", saveSubmit);
});

function alarmFormatter(cellvalue, options, rowdata){
    var grid = $(this);
    if(JSON.stringify(rowdata)!=='{}'){
        cellvalue = '<a href="javascript:0" opt-data="'+grid[0].id+'_delete" title="删除"><i class="fa fa-trash-o"></i></a>';
    }else{
        cellvalue = '';
    }
    return cellvalue;
}
function gridInit02(){
    var gridData02 = Object.create(gridData);
    gridData02.grid = $('#jgTable02');
    gridData02.pager = $('#jgPager02'); 
    gridData02.datatype = "local";
    gridData02.rowNum = '100';
    gridData02.colModel = [
        {label:'单号', name:'DocEntry', hidden:true},
        {label:'SKU', name:'SKU', width:60},
        {label:'物料描述', name:'ItemName'},
        {label:'上架备注', name:'Comment'},
        {label:'操作', name:'Options', width:40, formatter:alarmFormatter, sortable:false}
    ];  
    gridData02.scroll = true;
    gridData02.height = '390px';  
    gridData02.beforeRequest = function(){
        gridData02.grid.jqGrid("setGridParam", {
            data : Data02,
        });
    };
    gridData02.loadComplete = function(xhr){
        gridSize();
        var rowData = gridData02.grid.jqGrid("getRowData");
        $('a[opt-data="jgTable02_delete"]').unbind('click').bind('click',function(){
            var rowId = $(this).parent().parent()[0].id;
            Data02.forEach(function(v,i,a){
                // console.log(grid02.jqGrid("getRowData",rowId).SKU)
                // console.log(v.SKU)
                v.SKU === grid02.jqGrid("getRowData",rowId).SKU&&Data02.splice(i,1);
            });
            grid02.jqGrid("delRowData",rowId);
            // console.log(Data02)
        });
    };
    gridInit(gridData02);
}

function requestAjax(){ //MDM004203
    if(idx){
        var _postData = Object.create(postData);    //请求头
        _postData.Method = 'Q';
        _postData.Content = {
            "DocEntry": idx[1]
        }
        $.ajax({
            async: false,
            type: 'post', 
            url: mdmPath + '/MDM0042/MDM004203',
            data: _postData,
            dataType: 'json',
            success: function (re) {
                loadAjax(re);
            }
        });        
    }    
}
function loadAjax(re){
    if(re.Status==200){
        DocEntry.val(re.Content.DocEntry);  //单号
        DocDate.val(re.Content.DocDate);  //單據時間
        DocStatus.val(re.Content.DocStatus);    //單據狀態
        Comment.val(re.Content.Comment);    //备注
        $("#createDate").val(re.Content.CreateDate);    //
        $("#updateDate").val(re.Content.UpdateDate);    //
        $("#createUser").val(re.Content.CreateUser);    //
        $("#updateUser").val(re.Content.UpdateUser);    //
        Data02 = re.Content.MDM004202;
        //Data03 = re.Content.MDM004203;
        grid02.trigger('reloadGrid');
    } else if (re.Status == -999) {
        alert_QX($('body'), re.Message);
    } else {
        myAlert(re.Message);
    }
}

//Options
function addCode(){
    window.open('MDM004202.html', '_blank');     
}
function back(){
    window.open('MDM004201.html', '_self');
}
function uploadSKU(){
    var v = $('input[type="file"]').val()
    var formData = new FormData($('#uploadForm')[0]);
    // formData.append("Code", postData.Code);
    formData.append("Tonken", postData.Tonken);
    formData.append("BrowserID", postData.BrowserID);
    formData.append("UserCode", postData.UserCode);
    formData.append("Source", postData.Source);
    formData.append("Folder", 'GiftImages');
    if(v){
        $.ajax({
            url: mdmPath+'/MDM0042/MDM004204',
            type: 'post',
            //async: false,  
            cache: false,
            data: formData,
            success: function(re){
                re = JSON.parse(re);
                console.log(re);
                if(re.Status == 200){
                    myAlert('导入成功');
                    var reData = re.loMDM0042ExcelFiledList.rows;
                    console.log(reData)
                    reData.forEach(function(v,i,a){
                        Data02.push({
                            SKU: v.SKU,
                            ItemName: v.ItemName,
                            Comment: v.Comment
                        });
                    });
                    Data02 = Data02.unique('SKU');
                    grid02.trigger('reloadGrid');
                    $('input[type="file"]').val('');
                }else{
                    myAlert('导入失败');
                    // myAlert(re.MessageString);
                }
            },
            contentType: false,  
            processData: false,  
        });
    }else{
        myAlert('请选择要上传的文件');
    };
}
function saveSubmit(){  //MDM004201
    var MDM004202 = [];
    //var rowData = grid02.jqGrid("getRowData");
    Data02.forEach(function(v,i,a){
        MDM004202.push({
            DocEntry:DocEntry.val(),
            SKU:v.SKU,
            ItemName:v.ItemName,
            Comment:v.Comment,
            LineID:i,
            OrderById:i
        });
    });
    var requestData = {
        Content: {
            DocEntry: DocEntry.val(),    
            DocStatus: DocStatus.val(),
            DocDate: DocDate.val(),
            Comment: Comment.val(),
            MDM004202: MDM004202
        },
    }
    if(idx){
        requestData.Method = 'U'
    }else{
        requestData.Method = 'A';
        requestData.Content.DocEntry = '0';
        requestData.Content.DocDate = new Date().format("yyyy-MM-dd hh:mm:ss");
    }
    for(i in postData){
        requestData[i] = postData[i]
    }
    $('#uplading').removeClass('hidden');
    console.log(requestData);
    $.ajax({
        type: "post",
        url: mdmPath + '/MDM0042/MDM004201',
        data: requestData,
        dataType: "json",
        success: function(re) {
            if(re.Status==200){
                //myAlert('保存成功')
                window.open('MDM004202.html?DocEntry=' + re.Content.DocEntry, '_self');
            }else{
                myAlert(re.Message)
            }
        }
    });        
}

function gridSize(){ 
    grid02.setGridWidth($('.u_tabs_container').width() - 30);
}